//
//  AccountManager.swift
//  Git@OSC
//
//  Created by AeternChan on 11/22/15.
//  Copyright © 2015 oschina. All rights reserved.
//

import UIKit
import SwiftyJSON

class AccountManager: NSObject {
    
    static let kID = "id"
    static let kName = "name"
    static let kUserName = "username"
    static let kNewPortrait = "new_portrait"
    static let kPrivateToken = "private_token"
    static let kFollowers = "followers"
    static let kFollowing = "following"
    static let kStarred = "starred"
    static let kWatched = "watched"
    
    static var user: User?
    
    class func updateUser(newUser: User) {
        user = newUser
        persistUserInformation(newUser)
    }
    
    private class func persistUserInformation(user: User) {
        let userDefaults = NSUserDefaults.standardUserDefaults()
        
        userDefaults.setInteger(user.id, forKey: kID)
        userDefaults.setObject(user.name, forKey: kName)
        userDefaults.setObject(user.userName, forKey: kUserName)
        userDefaults.setURL(user.avatarURL, forKey: kNewPortrait)
        userDefaults.setObject(user.privateToken, forKey: kPrivateToken)
        userDefaults.setInteger(user.followersCount!, forKey: kFollowers)
        userDefaults.setInteger(user.followingCount!, forKey: kFollowing)
        userDefaults.setInteger(user.starredCount!, forKey: kStarred)
        userDefaults.setInteger(user.watchedCount!, forKey: kWatched)
        
        userDefaults.synchronize()
    }
    
    class func loadUserInformation() {
        let userDefaults = NSUserDefaults.standardUserDefaults()
        
        if let privateToken = userDefaults.objectForKey(kPrivateToken) {
            user = User()
            user?.id = userDefaults.integerForKey(kID)
            user?.name = userDefaults.objectForKey(kName) as! String
            user?.userName = userDefaults.objectForKey(kUserName) as! String
            user?.avatarURL = userDefaults.URLForKey(kNewPortrait)
            user?.privateToken = privateToken as? String
            user?.followersCount = userDefaults.integerForKey(kFollowers)
            user?.followingCount = userDefaults.integerForKey(kFollowing)
            user?.starredCount = userDefaults.integerForKey(kStarred)
            user?.watchedCount = userDefaults.integerForKey(kWatched)
        }
    }
}
